package com.wowangz.cms.systemmanage.databaseresource.api;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.store.pojo.StoreEntity;
import com.wowangz.cms.dailyoperation.store.service.StoreService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.databaseresource.pojo.DatabaseBinding;
import com.wowangz.cms.systemmanage.databaseresource.pojo.DatabaseResource;
import com.wowangz.cms.systemmanage.databaseresource.service.DatabaseBindingService;
import com.wowangz.cms.systemmanage.databaseresource.service.DatabaseResourceService;

@Scope("prototype")
@Controller
public class DatabaseBindingController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(DatabaseBindingController.class);
	
	@RequestMapping(value="/systemmanage/databasebinding/queryDatabaseBindingList.web")
	public String queryDatabaseBindingList(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/databaseresource/databasebindinglist";
	}
	
	/**
	 * 查看公司与数据库挂接列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="/systemmanage/databasebinding/queryDatabaseBindingListInfoDataGrid.json", method=RequestMethod.POST)
	public void queryDatabaseBindingListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		PangingParam pangingParam = null;
		DataResult  dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			
			map.put("startrow",dataGrid.getStartrow() );
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			map.put("state", SysConstant.CommonApproveStatus.OK);
			
			DatabaseBindingService databaseBindingService = (DatabaseBindingService)IssTransactionContainer.getInstance(DatabaseBindingService.class,false);
			long resultCount = databaseBindingService.findDatabaseBindingResultCount(map);
			List<DatabaseBinding> resultList = databaseBindingService.findDatabaseBindingResultList(map);
			
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("storeid", DataTypeConstant.LONG);
			dataStyle.addDepict("storecode", DataTypeConstant.STRING);
			dataStyle.addDepict("storename", DataTypeConstant.STRING);
			dataStyle.addDepict("dbid", DataTypeConstant.LONG);
			dataStyle.addDepict("ip", DataTypeConstant.STRING);
			dataStyle.addDepict("port", DataTypeConstant.STRING);
			dataStyle.addDepict("dbname", DataTypeConstant.STRING);
			dataStyle.addDepict("dbusername", DataTypeConstant.STRING);
			dataStyle.addDepict("totalconn", DataTypeConstant.STRING);
			dataStyle.addDepict("usedconn", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 进入挂接页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/systemmanage/databasebinding/toBindingDatabaseResource.web")
	public String toViewDatabaseResource(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String storeid = getRequest().getParameter("storeid");
			String dbid = getRequest().getParameter("dbid");
			StoreService storeService = (StoreService)IssTransactionContainer.getInstance(StoreService.class,false);
			StoreEntity storeEntity = storeService.findOne(new Long(storeid));
			model.addAttribute("storeEntity",storeEntity);
			if(dbid != null && !"0".equals(dbid))
			{
				DatabaseResourceService databaseresourceService = (DatabaseResourceService)IssTransactionContainer.getInstance(DatabaseResourceService.class,false);
				DatabaseResource databaseresource = databaseresourceService.findDatabaseResourceById(dbid);
				model.addAttribute("databaseresource", databaseresource);
			}
			//TODO 取得公司列表 前端选择公司分配资源
		} catch(Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/databaseresource/databasebindingView";
	}
	
	/**
	 * 挂接
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/systemmanage/databasebinding/bindingDatabaseResource.json", method={RequestMethod.GET,RequestMethod.POST})
	public String bindingDatabaseResource(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String dbid = request.getParameter("dbid");
			String storeid = request.getParameter("storeid");
			String olddbid = request.getParameter("olddbid");
			DatabaseResourceService databaseresourceService = (DatabaseResourceService)IssTransactionContainer.getInstance(DatabaseResourceService.class,true);
			DatabaseResource databaseresource = databaseresourceService.findDatabaseResourceById(dbid);
			DatabaseBindingService databaseBindingService = (DatabaseBindingService)IssTransactionContainer.getInstance(DatabaseBindingService.class,true);
			if(olddbid != null && !"".equals(olddbid))
			{
				if(!dbid.equals(olddbid))
				{
					databaseresource.setOlddbid(new Long(olddbid));
					databaseBindingService.updateDatabaseBinding(storeid,databaseresource);
				}
			}else
			{
				databaseBindingService.addDatabaseBinding(storeid,databaseresource);
			}
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.databasebinding.java.alert1"));
			userContext.setCloseWindow(true);
		} catch(ServiceException e)
		{
			e.printStackTrace();
			userContext.setErrorMessage(e.getMessage());
		}
		catch(Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.databasebinding.java.alert2"));
		}
		return "/WEB-INF/jsp/systemmanage/databaseresource/databasebindingView";
	}
	
	
}
